package system

import (
	"context"
	"github.com/gogf/gf/v2/util/gconv"
	"zuhao-seucre/internal/dao"
	"zuhao-seucre/internal/model/entity"
	"zuhao-seucre/internal/model/vo"
	"zuhao-seucre/internal/service"
	"zuhao-seucre/utility/collx"

	"zuhao-seucre/api/system/v1"
)

func (c *ControllerV1) GetUserInfo(ctx context.Context, req *v1.GetUserInfoReq) (res *v1.GetUserInfoRes, err error) {
	res = new(v1.GetUserInfoRes)
	user := service.ContextX().GetUser(ctx)
	// 角色信息
	var (
		roles          []*vo.AccountRoleVO
		sysAccountRole []*entity.TSysAccountRole
		sysRoles       []*entity.TSysRole
	)
	err = dao.TSysAccountRole.Ctx(ctx).Where(dao.TSysAccountRole.Columns().AccountId, user.UserId).Scan(&sysAccountRole)
	if err = dao.TSysAccountRole.Ctx(ctx).Where(dao.TSysAccountRole.Columns().AccountId, user.UserId).Scan(&sysAccountRole); err != nil {
		return
	}
	// 获取角色信息进行组装
	roleIds := collx.ArrayMap[*entity.TSysAccountRole, uint64](sysAccountRole, func(val *entity.TSysAccountRole) uint64 {
		return gconv.Uint64(val.RoleId)
	})
	err = dao.TSysRole.Ctx(ctx).WhereIn(dao.TSysRole.Columns().Id, roleIds).Scan(&sysRoles)
	// 转化成map
	roleId2Role := collx.ArrayToMap[*entity.TSysRole, uint64](sysRoles, func(val *entity.TSysRole) uint64 {
		return val.Id
	})
	for _, ac := range sysAccountRole {
		roleId := gconv.Uint64(ac.RoleId)
		role := roleId2Role[roleId]
		if role == nil {
			continue
		}
		roles = append(roles, &vo.AccountRoleVO{
			RoleId:     roleId,
			RoleName:   role.Name,
			Code:       role.Code,
			Status:     role.Status,
			CreateTime: ac.CreateTime, // 分配时间
			Creator:    ac.Creator,    // 分配者
		})
	}
	res.Roles = roles
	return
}
